/*************************************
 * Created by WebStorm
 * Author : 菲尔敦
 * QQ邮箱：2891044172@qq.com  手机号：15981761402
 * Created Time :2024/2/5 19:52
 Desc :路由守卫
 **************************************/
import type {Router, RouteRecordRaw} from 'vue-router';
import {Config} from '@/config'
import {useAsyncRouteStoreWidthOut} from '@/stores/app.ts'
import {ErrorPageRoute} from '@/router';
import {getToken} from '@/util/Auth.ts';

const BASE_LOGIN = Config.BASE_LOGIN; //登录页面
const BASE_HOME = Config.BASE_HOME; //首页地址

export function createRouterGuards(router: Router) {
    const asyncRouteStore = useAsyncRouteStoreWidthOut();
    asyncRouteStore.getConfig();
    router.beforeEach(async (to, from, next) => {
        const token = getToken();
        // @ts-ignore
        const Loading = window["$loading"] || null;
        Loading && Loading.start();
        //若token不存在就跳转登录页
        if (to.path !== BASE_LOGIN && !token) {
            next(BASE_LOGIN);
            await asyncRouteStore.tokenFailure();
            return;
        }
        if (to.path === BASE_LOGIN && !token) {
            next();
            await asyncRouteStore.tokenFailure();
            return;
        }
        //若token存在的情况下浏览器中输入登录页面地址自动会跳转到首页
        if (to.path === BASE_LOGIN && token) {
            next(BASE_HOME);
            return;
        }
        if (asyncRouteStore.isDynamicAddedRoute) {
            next();
            return;
        }
        const routes = await asyncRouteStore.generateRoutes();
        // 动态添加可访问路由表
        routes.forEach((item) => router.addRoute(item as unknown as RouteRecordRaw));
        //添加404
        const isErrorPage = router.getRoutes().findIndex((item) => item.name === ErrorPageRoute.name);
        if (isErrorPage === -1) {
            router.addRoute(ErrorPageRoute as unknown as RouteRecordRaw);
        }
        const redirectPath = (from.query.redirect || to.path) as string;
        const redirect = decodeURIComponent(redirectPath);
        const nextData = to.path === redirect ? {...to, replace: true} : {path: redirect};
        asyncRouteStore.setDynamicAddedRoute(true);
        next(nextData);
        return;
    })
    router.afterEach((to, _, _failure) => {
        const asyncRouteStore = useAsyncRouteStoreWidthOut();
        document.title = asyncRouteStore.title + "-" + (to?.meta?.title as string) || asyncRouteStore.title;
        // 在这里设置需要缓存的组件名称
        const keepAliveComponents = asyncRouteStore.keepAliveComponents;
        const currentComName: any = to.matched.find((item) => item.name == to.name)?.name;
        // 需要缓存的组件
        keepAliveComponents.push(currentComName);
        asyncRouteStore.setKeepAliveComponents(keepAliveComponents);
        // @ts-ignore
        const Loading = window["$loading"] || null;
        Loading && Loading.finish();
    })
    router.onError((error) => {
        console.log(error, "路由错误");
    });
}